﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Xms.Abp;

public static class ConsoleManager
{
    private const string Kernel32_DllName = "kernel32.dll";
    [DllImport(Kernel32_DllName)]
    private static extern bool AllocConsole();
    [DllImport(Kernel32_DllName)]
    private static extern bool FreeConsole();
    [DllImport(Kernel32_DllName)]
    private static extern IntPtr GetConsoleWindow();
    [DllImport(Kernel32_DllName)]
    private static extern int GetConsoleOutputCP();
    public static bool HasConsole
    {
        get { return GetConsoleWindow() != IntPtr.Zero; }
    }
    /// Creates a new console instance if the process is not attached to a console already.  
    public static void Show()
    {
        if (!HasConsole && Debugger.IsAttached)
        {
            AllocConsole();
        }
    }
    /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.   
    public static void Hide()
    {
        if (HasConsole)
        {
            FreeConsole();
        }
    }
    public static void Toggle()
    {
        if (HasConsole)
        {
            Hide();
        }
        else
        {
            Show();
        }
    }
}

